package com.lagou.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class GroupChatNioServer {

    private ServerSocketChannel serverSocketChannel;
    private Selector selector;
    private final static int PORT = 6667;

    public GroupChatNioServer() {
        try {
            serverSocketChannel = ServerSocketChannel.open();
            selector = Selector.open();
            serverSocketChannel.bind(new InetSocketAddress(PORT));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("server started at :" + PORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        try {
            while (true) {
                if (selector.select(1000) > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        if (key.isAcceptable()) {
                            // 有新的连接
                            ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                            SocketChannel accept = channel.accept();
                            System.out.println("有新的客户端连接：地址为" + accept.getRemoteAddress());
                            accept.configureBlocking(false);
                            accept.register(selector, SelectionKey.OP_READ);
                        }
                        // 读取数据
                        if (key.isReadable()) {
                            try {
                                // 获取通道
                                SocketChannel channel = (SocketChannel) key.channel();
                                ByteBuffer allocate = ByteBuffer.allocate(1024);
                                int readLen = 0;
                                StringBuilder stringBuilder = new StringBuilder();
                                while ((readLen = channel.read(allocate)) > 0) {
                                    byte[] array = allocate.array();
                                    stringBuilder.append(new String(array, 0, readLen));
                                }
                                String msg = stringBuilder.toString();
                                msg = "客户端-" + channel.getRemoteAddress().toString().substring(1) + "-发送的消息为：" + msg;
                                // 打印消息到控制台
                                System.out.println(msg);
                                // 转发给其他群聊成员
                                sendMsg2Others(msg, key);
                            } catch (IOException e) {
                                System.out.println("客户端" + ((SocketChannel) key.channel()).getRemoteAddress().toString().substring(1) + "下线。。");
                                key.channel().close();
                                key.cancel();
//                                e.printStackTrace();
                            }
                        }
                        iterator.remove();
                    }
                }
                // 防止重复消费
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendMsg2Others(String msg, SelectionKey key) {
        try {
            Set<SelectionKey> keys = selector.keys();
            for (SelectionKey selectionKey : keys) {
                SelectableChannel selectableChannel = selectionKey.channel();
                // 发给其他成员
                if (selectableChannel instanceof SocketChannel && selectionKey != key) {
                    SocketChannel channel = null;
                    try {
                        channel = (SocketChannel)selectableChannel;
                        ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                        channel.write(wrap);
                    } catch (IOException e) {
                        System.out.println("--> 客户端：" + channel.getRemoteAddress() + "- 已经下线...");
                        selectionKey.cancel();
                        channel.close();
                        e.printStackTrace();
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        GroupChatNioServer nioServer = new GroupChatNioServer();
        nioServer.listen();
    }
}
